package cn.yangjunda.hibernate_pagehelper;

import cn.yangjunda.hibernate_pagehelper.ErrorParser.impl.AbstractParser;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import java.util.List;

/**
 * Created by juanda on 12/6/17.
 */
public class SqlUtil {

    public SqlUtil() {
    }

    public static int getCount(String hql){
        SessionFactory sessionFactory = HibernateInitializationUtil.getSessionFactory();
        Session session=sessionFactory.openSession();
        Transaction transaction=session.beginTransaction();
        Query query;
        try {
            query = session.createQuery(AbstractParser.newParser(Dialect.mysql).getCountSql(hql));
        }catch (StringIndexOutOfBoundsException siobe){
            throw new RuntimeException("分页语句必须是包含from关键词的Select查询!");
        }catch (NullPointerException nullPointerException){
            throw new RuntimeException("分页语句不能为空!");
        }
        transaction.commit();
        return ((Number)query.uniqueResult()).intValue();
    }

    public static Page getPage(String hql, int pageNum, int pageSize,String orderBy){
        SessionFactory sessionFactory = HibernateInitializationUtil.getSessionFactory();
        Session session=sessionFactory.openSession();
        Transaction transaction=session.beginTransaction();
        Query query;
        try {
            query = session.createQuery(AbstractParser.newParser(Dialect.mysql).getPageSql(hql,orderBy)).setFirstResult((((pageNum-1)*pageSize)-1)<=0?0:(((pageNum-1)*pageSize)-1)).setMaxResults(pageSize);
        }catch (StringIndexOutOfBoundsException stringIndexOutOfBoundsException){
            throw new RuntimeException("分页语句必须是包含from关键词的Select查询!");
        }catch (NullPointerException nullPointerException){
            throw new RuntimeException("分页语句不能为空!");
        }
        List list = query.list();
        Page page = new Page();
        for (Object object: list){
            page.add(object);
        }
        transaction.commit();
        session.close();
        return page;
    }
}
